<template>
  <div class="household-add-container">
    <el-card class="household-add-card">
      <template #header>
        <div class="card-header">
          <span>新增房户</span>
          <div class="header-buttons">
            <el-button @click="handleBack">
              <el-icon><ArrowLeft /></el-icon>
              返回列表
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 选择区域 -->
      <div class="selection-area">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="社区" required>
              <el-select
                v-model="selectedCommunity"
                placeholder="请选择社区"
                style="width: 100%"
                clearable
                @change="handleCommunityChange"
              >
                <el-option
                  v-for="item in communityList"
                  :key="item.id"
                  :label="item.communityName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="楼栋" required>
              <el-select
                v-model="selectedBuilding"
                placeholder="请选择楼栋"
                style="width: 100%"
                clearable
                :disabled="!selectedCommunity"
                @change="handleBuildingChange"
              >
                <el-option
                  v-for="item in buildingList"
                  :key="item.id"
                  :label="item.buildingName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单元" required>
              <el-select
                v-model="selectedUnit"
                placeholder="请选择单元"
                style="width: 100%"
                clearable
                :disabled="!selectedBuilding"
                @change="handleUnitChange"
              >
                <el-option
                  v-for="item in unitList"
                  :key="item.id"
                  :label="item.unitName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
      </div>
      
      <!-- 房户信息表单 -->
      <div class="form-area" v-if="selectedUnit">
        <el-divider content-position="left">房户信息</el-divider>
        
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="120px"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="房户编号" prop="householdCode">
                <el-input
                  v-model="formData.householdCode"
                  placeholder="请输入房户编号"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="房间号" prop="roomNumber">
                <el-input
                  v-model="formData.roomNumber"
                  placeholder="请输入房间号"
                  maxlength="10"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="所属社区" prop="communityName">
                <el-input v-model="formData.communityName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属楼栋" prop="buildingName">
                <el-input v-model="formData.buildingName" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="所属单元" prop="unitName">
                <el-input v-model="formData.unitName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="楼层号" prop="floorNumber">
                <el-input-number
                  v-model="formData.floorNumber"
                  :min="1"
                  :max="100"
                  placeholder="请输入楼层号"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="房屋面积" prop="area">
                <el-input-number
                  v-model="formData.area"
                  :min="1"
                  :max="1000"
                  :precision="2"
                  placeholder="请输入房屋面积"
                  style="width: 100%"
                />
                <span class="unit-text">平方米</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="使用面积" prop="usableArea">
                <el-input-number
                  v-model="formData.usableArea"
                  :min="1"
                  :max="1000"
                  :precision="2"
                  placeholder="请输入使用面积"
                  style="width: 100%"
                />
                <span class="unit-text">平方米</span>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="朝向" prop="orientation">
                <el-select
                  v-model="formData.orientation"
                  placeholder="请选择朝向"
                  style="width: 100%"
                >
                  <el-option label="东" value="东" />
                  <el-option label="南" value="南" />
                  <el-option label="西" value="西" />
                  <el-option label="北" value="北" />
                  <el-option label="东南" value="东南" />
                  <el-option label="西南" value="西南" />
                  <el-option label="东北" value="东北" />
                  <el-option label="西北" value="西北" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="房间类型" prop="roomType">
                <el-select
                  v-model="formData.roomType"
                  placeholder="请选择房间类型"
                  style="width: 100%"
                >
                  <el-option label="一室" :value="1" />
                  <el-option label="两室" :value="2" />
                  <el-option label="三室" :value="3" />
                  <el-option label="四室及以上" :value="4" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="产权类型" prop="propertyType">
                <el-select
                  v-model="formData.propertyType"
                  placeholder="请选择产权类型"
                  style="width: 100%"
                >
                  <el-option label="自有" :value="1" />
                  <el-option label="租赁" :value="2" />
                  <el-option label="其他" :value="3" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="房产证号" prop="propertyCertificate">
                <el-input
                  v-model="formData.propertyCertificate"
                  placeholder="请输入房产证号"
                  maxlength="100"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="购买日期" prop="purchaseDate">
                <el-date-picker
                  v-model="formData.purchaseDate"
                  type="date"
                  placeholder="请选择购买日期"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="房户状态" prop="status">
                <el-select
                  v-model="formData.status"
                  placeholder="请选择房户状态"
                  style="width: 100%"
                >
                  <el-option label="空置" :value="0" />
                  <el-option label="已入住" :value="1" />
                  <el-option label="装修中" :value="2" />
                  <el-option label="出租" :value="3" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="物业费单价" prop="propertyFeeRate">
                <el-input-number
                  v-model="formData.propertyFeeRate"
                  :min="0"
                  :max="100"
                  :precision="2"
                  placeholder="请输入物业费单价"
                  style="width: 100%"
                />
                <span class="unit-text">元/平方米</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="装修状态" prop="decorationStatus">
                <el-select
                  v-model="formData.decorationStatus"
                  placeholder="请选择装修状态"
                  style="width: 100%"
                >
                  <el-option label="毛坯" :value="0" />
                  <el-option label="简装" :value="1" />
                  <el-option label="精装" :value="2" />
                  <el-option label="豪装" :value="3" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="房户描述" prop="description">
                <el-input
                  v-model="formData.description"
                  type="textarea"
                  placeholder="请输入房户描述"
                  :rows="3"
                  maxlength="500"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        
        <!-- 操作按钮 -->
        <div class="form-actions">
          <el-button @click="handleBack">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            创建房户
          </el-button>
        </div>
      </div>
      
      <!-- 提示信息 -->
      <div class="tip-area" v-if="!selectedUnit">
        <el-alert
          title="操作提示"
          type="info"
          :closable="false"
          show-icon
        >
          <template #default>
            <p>请按照社区 → 楼栋 → 单元的顺序进行选择</p>
            <p>选择完成后，系统将显示房户信息表单供您填写</p>
          </template>
        </el-alert>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
/**
 * 房户新增页面
 * @author Wu.Liang
 * @date 2025-01-30
 */
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { householdApi } from '@/api/household'
import { buildingApi } from '@/api/building'
import { unitApi } from '@/api/unit'
import { communityApi } from '@/api/community'
import { householdFormRules } from '@/types/region'
import { useUserStore } from '@/store/user'

// 初始化router
const router = useRouter()

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const formRef = ref()

// 选择数据
const selectedCommunity = ref<number | undefined>(undefined)
const selectedBuilding = ref<number | undefined>(undefined)
const selectedUnit = ref<number | undefined>(undefined)

// 列表数据
const communityList = ref<any[]>([])
const buildingList = ref<any[]>([])
const unitList = ref<any[]>([])

// 表单数据
const formData = reactive({
  householdCode: '',
  roomNumber: '',
  communityId: undefined as number | undefined,
  buildingId: undefined as number | undefined,
  unitId: undefined as number | undefined,
  communityName: '',
  buildingName: '',
  unitName: '',
  floorNumber: 1,
  area: 0,
  usableArea: 0,
  orientation: '',
  roomType: 1,
  propertyType: 1,
  propertyCertificate: '',
  purchaseDate: '',
  propertyFeeRate: 0,
  status: 0,
  decorationStatus: 0,
  description: ''
})

// 表单验证规则
const formRules = householdFormRules



// 社区变化处理
const handleCommunityChange = async (communityId: number | undefined) => {
  selectedBuilding.value = undefined
  selectedUnit.value = undefined
  buildingList.value = []
  unitList.value = []
  resetFormData()
  
  if (communityId) {
    try {
      const response = await buildingApi.getBuildingsByCommunity(communityId)
      buildingList.value = (response.data || []).filter((item: any) => item.id != null)
      
      // 更新表单数据
      const community = communityList.value.find(item => item.id === communityId)
      if (community) {
        formData.communityId = communityId
        formData.communityName = community.communityName
      }
    } catch (error) {
      ElMessage.error('加载楼栋数据失败')
    }
  }
}

// 楼栋变化处理
const handleBuildingChange = async (buildingId: number | undefined) => {
  selectedUnit.value = undefined
  unitList.value = []
  resetFormData()
  
  if (buildingId) {
    try {
      const response = await unitApi.getUnitsByBuilding(buildingId)
      unitList.value = (response.data || []).filter((item: any) => item.id != null)
      
      // 更新表单数据
      const building = buildingList.value.find(item => item.id === buildingId)
      if (building) {
        formData.buildingId = buildingId
        formData.buildingName = building.buildingName
      }
    } catch (error) {
      ElMessage.error('加载单元数据失败')
    }
  }
}

// 单元变化处理
const handleUnitChange = async (unitId: number | undefined) => {
  resetFormData()
  
  if (unitId) {
    try {
      // 更新表单数据
      const unit = unitList.value.find(item => item.id === unitId)
      if (unit) {
        formData.unitId = unitId
        formData.unitName = unit.unitName
      }
    } catch (error) {
      ElMessage.error('加载单元数据失败')
    }
  }
}





// 重置表单数据
const resetFormData = () => {
  Object.assign(formData, {
    householdCode: '',
    roomNumber: '',
    communityId: undefined,
    buildingId: undefined,
    unitId: undefined,
    communityName: '',
    buildingName: '',
    unitName: '',
    floorNumber: 1,
    area: 0,
    usableArea: 0,
    orientation: '',
    roomType: 1,
    propertyType: 1,
    propertyCertificate: '',
    purchaseDate: '',
    propertyFeeRate: 0,
    status: 0,
    decorationStatus: 0,
    description: ''
  })
}

// 加载社区列表（根据用户数据权限）
const loadCommunityList = async () => {
  try {
    const userStore = useUserStore()
    await userStore.checkAndUpdateCompanyInfo()
    
    const response = await communityApi.getCommunityList({})
    communityList.value = (response.data || []).filter((item: any) => item.id != null)
  } catch (error) {
    ElMessage.error('加载社区数据失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    
    if (!formData.communityId || !formData.buildingId || !formData.unitId) {
      ElMessage.error('请先选择社区、楼栋和单元')
      return
    }
    
    submitting.value = true
    
    await householdApi.createHousehold(formData)
    
    ElMessage.success('房户创建成功')
    handleBack()
  } catch (error) {
    if (error !== false) {
      ElMessage.error('创建失败')
    }
  } finally {
    submitting.value = false
  }
}

// 返回列表
const handleBack = () => {
  router.push('/region/household')
}

// 组件挂载时初始化
onMounted(() => {
  loadCommunityList()
})
</script>

<style lang="scss" scoped>
.household-add-container {
  padding: 20px;
  
  .household-add-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-buttons {
        display: flex;
        gap: 10px;
      }
    }
    
    .selection-area {
      margin-bottom: 30px;
      padding: 20px;
      background-color: #f5f7fa;
      border-radius: 4px;
    }
    
    .form-area {
      .form-actions {
        margin-top: 30px;
        text-align: center;
        
        .el-button {
          margin: 0 10px;
        }
      }
    }
    
    .tip-area {
      margin-top: 20px;
      
      .el-alert {
        .el-alert__content {
          p {
            margin: 5px 0;
            color: #606266;
          }
        }
      }
    }
  }
}

.unit-text {
  margin-left: 8px;
  color: #909399;
  font-size: 14px;
}
</style>
